/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2022-04-21 20:16:34
 * @LastEditors: GGB
 * @LastEditTime: 2022-04-23 12:20:12
 */
import type { App } from 'vue'
import type { I18n, I18nOptions } from 'vue-i18n'

import { createI18n } from 'vue-i18n'
import { setLoadLocalePool } from './helper'
import { localeSetting } from '/@/settings/localeSetting'
import { useLocaleStoreWithOut } from '/@/store/modules/locale'
import zh_CN from './lang/zh_CN'
import en from './lang/en'

const { fallback, availableLocales } = localeSetting

export let i18n: ReturnType<typeof createI18n>

async function createI18nOptions(): Promise<I18nOptions> {
  const localeStore = useLocaleStoreWithOut()
  const locale = localeStore.getLocale
  // 这里改用另外一种方式
  // const defaultLocal = await import(`./lang/${locale}.ts`);
  // const message = defaultLocal.default?.message ?? {};
  const messages: Record<string, any> = {
    en,
    zh_CN,
  }
  // // const defaultLocal = zh_CN;
  // const message = defaultLocal ?? {};
  const message = messages[locale].message ?? {}

  setLoadLocalePool((loadLocalePool) => {
    loadLocalePool.push(locale)
  })

  return {
    legacy: true,
    locale,
    fallbackLocale: fallback,
    globalInjection: true,
    messages: {
      [locale]: message,
    },
    availableLocales,
    sync: true, // If you don’t want to inherit locale from global scope, you need to set sync of i18n component option to false.
    silentTranslationWarn: true, // true - warning off
    missingWarn: false,
    silentFallbackWarn: true,
  }
}

// setup i18n instance with glob
export async function setupI18n(app: App) {
  const options = await createI18nOptions()
  i18n = createI18n(options) as I18n
  app.use(i18n)
}
